<template>
  <div class="a">
    <el-alert title="消息提示的文案" type="info" show-icon center> </el-alert>
    <el-tabs
      :tab-position="'left'"
      :before-leave="beforeTog"
      v-model="name"
      @tab-click="handleClick"
      style="margin-top: 50px"
    >
      <el-tab-pane label="基本信息" name="0">
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
          label-position="top"
        >
          <el-form-item label="商品名称" prop="goods_name">
            <el-input v-model="ruleForm.goods_name"></el-input>
          </el-form-item>
          <el-form-item label="商品价格" prop="goods_price">
            <el-input v-model="ruleForm.goods_price"></el-input>
          </el-form-item>
          <el-form-item label="商品重量" prop="goods_weight">
            <el-input v-model="ruleForm.goods_weight"></el-input>
          </el-form-item>
          <el-form-item label="商品数量" prop="goods_number">
            <el-input v-model="ruleForm.goods_number"></el-input>
          </el-form-item>
          <el-form-item label="商品分类" prop="goods_cat">
            <el-cascader
              :options="tableData"
              :props="{
                expandTrigger: 'hover',
                label: 'cat_name',
                value: 'cat_id',
              }"
              @change="handleChange"
            ></el-cascader>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="商品参数" name="1">
        <div
          v-for="item in tableData1"
          :key="item.attr_id"
          style="margin: 15px"
        >
          <p style="margin-buttom: 10px">{{ item.attr_name }}</p>
          <el-checkbox-group v-model="checkboxGroup1" size="small">
            <el-checkbox
              :label="i"
              border
              :key="i"
              v-for="i in item.attr_vals"
              @change="tog"
            ></el-checkbox>
          </el-checkbox-group>
        </div>
      </el-tab-pane>
      <el-tab-pane label="商品属性" name="2">
        <div v-for="item in tableData2" :key="item.attr_id">
          <p style="margin: 10px 0">{{ item.attr_name }}</p>
          <el-input v-model="item.attr_vals"></el-input>
        </div>
      </el-tab-pane>
      <el-tab-pane label="商品图片" name="3">
        <el-upload
          class="upload-demo"
          :action="upUrl"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          list-type="picture"
          :headers="he"
          :on-success="handleSuccess"
        >
          <el-button size="small" type="primary">点击上传</el-button>
        </el-upload>
        <el-dialog
          :visible.sync="dialogVisible"
          width="600px"
        >
          <img :src="url" style="width:100%">
        </el-dialog>
      </el-tab-pane>
      <el-tab-pane label="商品内容" name="4">
        <quill-editor v-model="ruleForm.goods_introduce"></quill-editor>
        <el-button type="primary" @click="add">添加商品</el-button>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
export default {
  data() {
    return {
      name: "0",
      dialogVisible:false,
      checkboxGroup1: [],
      ruleForm: {
        goods_name: "1",
        goods_price: 1, //商品价格
        goods_number: 1, //商品数量
        goods_weight: 1, //商品重量
        goods_cat: "", //商品分类
        goods_introduce: "", //商品详细信息描述
        pics: [], //商品图片
        attrs: [], //商品参数
      },
      temUrl: "",
      // 基本信息校验
      rules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
        ],
      },
      upUrl: "https://www.liulongbin.top:8888/api/private/v1/upload",
      tableData: [], //分类列表
      tableData1: [], //动态参数
      tableData2: [], //静态属性
      typeid: "", //当前选中的分类id
      he: {
        Authorization: localStorage.getItem("token"), //上传图片需要请求头
      },
      url: "",
    };
  },
  created() {
    this.$store.dispatch("getgoods").then((res) => {
      if (res.data.meta.status == 200) {
        this.tableData = res.data.data;
      }
    });
  },
  mounted() {},
  methods: {
    tog() {
      console.log(this.checkboxGroup1);
    },
    handleChange(val) {
      this.ruleForm.goods_cat = val.join(",");
      this.typeid = val[val.length - 1];
    },
    // 在tab切换之前进行判断 第一个参数是新的name名，第二个是旧的name名
    beforeTog(a, b) {
      let flag = false;
      // 判断表单是否为空
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          flag = true;
        } else {
          this.$message.error("请填写基本信息");
          return false;
        }
      });
      // 判断商品分类id存在并且表单内容都不为空可以跳转tab
      if (this.typeid && flag) {
        // 商品参数
        if (a == 1) {
          this.$store
            .dispatch("jd", { id: this.typeid * 1, sel: "many" })
            .then((res) => {
              if (res.meta.status == 200) {
                this.$message.success(res.meta.msg);
                // 通过深拷贝获得请求的数据，再添加自己的值和input框的状态
                let data = JSON.parse(JSON.stringify(res.data));
                data.forEach((item) => {
                  item.attr_vals = item.attr_vals
                    ? item.attr_vals.split(",")
                    : [];
                  item.inputValue = "";
                  item.inputVisible = false;
                });
                this.tableData1 = data;
              }
            });
        }
        // 商品属性
        else if (a == 2) {
          this.$store
            .dispatch("jd", { id: this.typeid * 1, sel: "only" })
            .then((res) => {
              if (res.meta.status == 200) {
                this.$message.success(res.meta.msg);
                // 通过深拷贝获得请求的数据，再添加自己的值和input框的状态
                let data = JSON.parse(JSON.stringify(res.data));
                data.forEach((item) => {
                  item.attr_vals = item.attr_vals ? item.attr_vals : "";
                  item.inputValue = "";
                  item.inputVisible = false;
                });
                console.log(data);
                this.tableData2 = data;
              }
            });
        }
      }
      // 判断表单不为空，并且没有商品分类id，不允许跳转tab
      else if (flag && this.typeid == "") {
        this.$message.error("请选择商品分类");
        return false;
      }
      // 上面两个都不满足不允许跳转tab
      else {
        return false;
      }
    },
    handleClick(a, b) {},
    // 删除图片触发
    handleRemove(file) {
      console.log(file);
      this.ruleForm.pics.forEach((item, i) => {
        if (item.pic == file.response.data.tmp_path) {
          this.ruleForm.pics.splice(i, 1);
        }
      });
    },
    // 点击图片触发
    handlePreview(file) {
      this.dialogVisible = true;
      this.url = file.response.data.url;
    },
    closeViewer() {
      this.showViewer = false;
    },
    // 上传图片成功触发
    handleSuccess(file) {
      if (file.meta.status == 200) {
        this.$message.success(file.meta.msg);
        this.temUrl = file.data.tmp_path;
        this.ruleForm.pics.push({ pic: this.temUrl });
      }
    },
    // 添加商品
    add() {
      this.tableData1.forEach((item) => {
        let obj = {
          attr_id: item.attr_id,
          attr_value: item.attr_vals,
        };
        this.ruleForm.attrs.push(obj);
      });
      this.tableData2.forEach((item) => {
        let obj1 = {
          attr_id: item.attr_id,
          attr_value: item.attr_vals,
        };
        this.ruleForm.attrs.push(obj1);
      });
      this.$store.dispatch("addGoods", this.ruleForm).then((res) => {
        if (res.meta.status == 201) {
          this.$message.success(res.meta.msg);
          this.$router.push("/goods");
        }
      });
    },
  },
};
</script>

<style scoped lang='scss'>
.a {
  padding-bottom: 20px;
}
::v-deep .ql-editor {
  min-height: 300px !important;
}
</style>
